package org.feng.error;

import cn.dev33.satoken.exception.SaTokenException;
import lombok.extern.slf4j.Slf4j;
import org.feng.base.entity.Result;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 异常处理
 *
 * @author : FengShuai
 * @since : 2024/6/27 9:24
 */
@Slf4j
@RestControllerAdvice
public class ErrorHandler {
    /**
     * 不支持的请求方式
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public Result<String> httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) {
        String method = exception.getMethod();
        log.error(exception.getMessage(), exception);
        return Result.error("不支持" + method + "请求");
    }

    /**
     * 请求参数不对异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<String> methodArgumentNotValidException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        StringBuilder message = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            message.append(fieldError.getDefaultMessage()).append(";");
        }
        log.error(exception.getMessage(), exception);
        return Result.error(message.toString());
    }

    /**
     * 登录token异常
     */
    @ExceptionHandler(value = SaTokenException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<String> saTokenException(SaTokenException exception) {
        log.error(exception.getMessage(), exception);
        return Result.error(exception.getMessage());
    }

    /**
     * 参数缺失异常
     */
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public Result<String> missingServletRequestParameterException(MissingServletRequestParameterException exception) {
        log.error(exception.getMessage(), exception);
        String parameterName = exception.getParameterName();
        return Result.error(parameterName + "参数缺失");
    }

    /**
     * 通用异常
     */
    @ExceptionHandler(value = Exception.class)
    public Result<String> exception(Exception exception) {
        log.error(exception.getMessage(), exception);
        return Result.error(exception.getMessage());
    }
}
